<?php
/**
 * OAuth2 Service
 * User: zng
 * Date: 2020/3/19
 * Time: 16:20
 */
namespace app\api\service\user;

use app\exceptions\OrdinaryException;

Class OAuth2 {

    /**
     * 第三方登录配置数组
     * @var array
     */
    private $_secrets;

    /**
     * 第三方接口名称数组
     * @var array
     */
    private $_secretKeys;

    public function __construct()
    {
        $this->_secrets = config('secret.');
        $this->_secretKeys = array_keys($this->_secrets);
    }

    /**
     * 第三方登录授权操作
     * @param string $code code码
     * @param string $state 来源
     * @return array
     */
    public function handle( string $code, string $state )
    {
        //判断配置是否为真
        if ( ! $this->_secrets[$state] || ! is_array($this->_secrets[$state]) ) {
            throw new OrdinaryException('服务器配置错误');
        }
        $action = $state.'_third_info';
        $data = $this->$action($code);

        return $data;
    }

    /**
     * 微信小程序登录
     * @param string $code code码
     * @throws OrdinaryException
     * @return array
     */
    private function xcx_third_info(string $code)
    {
        $params = [];
        $params['appid'] = $this->_secrets['xcx']['appid'];
        $params['secret'] = $this->_secrets['xcx']['secret'];
        $params['js_code'] = $code;
        $params['grant_type'] = $this->_secrets['xcx']['grant_type'];
        $url = $this->_secrets['xcx']['uri']['request_uri'].'?'.http_build_query($params);

        $request_data = json_decode(curl_req($url), true);

        if (  ! $request_data || ! isset($request_data['openid']) || ! $request_data['openid'] ) {
            throw new OrdinaryException($request_data['errmsg']??'AUTH_FAILED');
        }

        return $request_data;
    }

}